package com.gc;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by Lxk on 2019/2/26.
 */

class RWLock {
    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public void read(){
        lock.readLock().lock();
        try{
            System.out.println(Thread.currentThread() + "read");
            Thread.sleep(1000);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.readLock().unlock();
        }
    }

    public void write(){
        lock.writeLock().lock();
        try{
            System.out.println(Thread.currentThread() + "write");
            Thread.sleep(1000);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.writeLock().unlock();
        }
    }
}


class ReadThread extends Thread {
    private RWLock lock;

    public ReadThread(RWLock lock){
        this.lock = lock;
    }

    public void run(){
        lock.read();
    }

}

class WriteThread extends Thread {

    private RWLock lock;

    public WriteThread(RWLock lock){
        this.lock = lock;
    }

    public void run(){
        lock.write();
    }

}


public class ReadWriteLockTest {

    public static void main(String[] args) throws InterruptedException {
        RWLock lock = new RWLock();
        ReadThread readThread = new ReadThread(lock);
        ReadThread readThread2 = new ReadThread(lock);
        WriteThread writeThread = new WriteThread(lock);
        readThread.start();
        readThread2.start();
        writeThread.start();
        Thread.sleep(6000);
        System.out.println("main,,,");
    }


}
